<template>
  <div v-loading="loading">
    <FixedOperation>
      <div class="flex items-center justify-between">
        <div class="leading-30px">
          <div class="inline-block">
            <svg-icon
              :icon-class="'svg_salesorder'"
              class="w-30px h-30px align-middle"
            />
            <span
              class="text-#000 leading-30px ml-10px text-16px font-bold align-bottom"
              >供应商准入申请</span
            >
          </div>
          <div
            class="inline-block text-15px ml-10px"
            style="vertical-align: bottom"
            v-if="bpmnStatus"
          >
            <i
              :class="
                bpmnStatus == '审批通过'
                  ? 'h-8px w-8px bg-#fe9400 inline-block rounded'
                  : bpmnStatus == '流程未发起'
                  ? 'h-8px w-8px bg-#ccc inline-block rounded'
                  : 'h-8px w-8px bg-#10d070 inline-block rounded'
              "
            ></i>
            {{ bpmnStatus }}
          </div>
        </div>
        <div class="text-right">
          <slot></slot>
          <el-button
            type="primary"
            plain
            @click="handleSubmit('examine')"
            v-if="isExamine && isCanStart && formData.formType == 'add'"
            >发起申请</el-button
          >
          <el-button
            type="primary"
            @click="handleSubmit('save')"
            v-if="!formDisabled"
            >保存</el-button
          >
          <!-- <el-button @click="handleReset(form)" v-if="isCanStart"
            >重置</el-button
          > -->
          <el-button type="primary" plain @click="handleReturn">返回</el-button>
        </div>
      </div>
    </FixedOperation>
    <div class="app-container form-box">
      <el-form
        ref="form"
        :model="formData"
        :rules="formData.formType == 'add' ? formRules : formRulesA8"
        :disabled="formDisabled"
        label-width="150px"
      >
        <el-collapse v-model="activeNames">
          <!-- 基本信息 -->
          <el-collapse-item name="1" disabled>
            <template #title>
              <TitleName
                title="供应商基本信息"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <el-row :gutter="80">
              <el-col :span="12">
                <el-form-item label="供应商来源" prop="type">
                  <el-radio-group
                    v-model="formData.type"
                    @change="typeChange"
                    :disabled="fieldDisabled.includes('供应商来源')"
                  >
                    <el-radio-button
                      v-for="item in supplier_type_1"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio-button
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商名称" prop="supplierName">
                  <el-input
                    v-model="formData.supplierName"
                    placeholder="请输入供应商名称"
                    :disabled="
                      formData.formType == 'a8' ||
                      fieldDisabled.includes('供应商名称')
                    "
                  >
                    <template #append v-if="hasPermi('supplierA8:add')">
                      <el-button
                        icon="Search"
                        @click="addA8Supplier()"
                        v-hasPermi="['supplierA8:add']"
                        :disabled="
                          formData.formType == 'a8' ||
                          fieldDisabled.includes('供应商名称')
                        "
                      />
                      <!-- <el-tooltip
                        class="box-item"
                        effect="dark"
                        content="只可供应商管理员可用"
                        placement="top-start"
                        ><div>
                          <el-button
                            icon="Search"
                            @click="addA8Supplier()"
                            v-hasPermi="['supplierA8:add']"
                            :disabled="
                              formData.formType == 'a8' ||
                              fieldDisabled.includes('供应商名称')
                            "
                          />
                        </div>
                      </el-tooltip> -->
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="统一社会信用代码" prop="supplierTaxcode">
                  <el-input
                    v-model="formData.supplierTaxcode"
                    placeholder="请输入统一社会信用代码"
                    :disabled="
                      formData.formType == 'a8' ||
                      fieldDisabled.includes('统一社会信用代码')
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.formType == 'a8'">
                <el-form-item label="到期时间" prop="expireDate">
                  <el-date-picker
                    style="width: 100%"
                    v-model="formData.expireDate"
                    type="date"
                    placeholder="到期时间"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type != '3'">
                <el-form-item label="类型" prop="supplierType">
                  <el-input
                    v-model="formData.supplierType"
                    placeholder="请输入类型"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="地址" prop="address">
                  <el-input
                    v-model="formData.address"
                    placeholder="请输入地址"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type != '3'">
                <el-form-item label="法定代表人" prop="legalRepresentative">
                  <el-input
                    v-model="formData.legalRepresentative"
                    placeholder="请输入法定代表人"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type != '3'">
                <el-form-item label="注册资本" prop="registeredCapital">
                  <el-input
                    v-model="formData.registeredCapital"
                    placeholder="请输入注册资本"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type != '3'">
                <el-form-item label="营业期限" prop="businessTerm">
                  <el-input
                    v-model="formData.businessTerm"
                    placeholder="请输入营业期限"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="开户银行" prop="depositBank">
                  <el-input
                    v-model="formData.depositBank"
                    placeholder="请输入开户银行"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="银行账号" prop="bankAccount">
                  <el-input
                    v-model="formData.bankAccount"
                    placeholder="请输入银行账号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联行号" prop="interbankNumber">
                  <el-input
                    v-model="formData.interbankNumber"
                    placeholder="请输入联行号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type != '3'">
                <el-form-item label="系统征信分值" prop="creditScore">
                  <el-input
                    v-model="formData.creditScore"
                    placeholder="请输入系统征信分值"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type != '3'">
                <el-form-item label="信用级别" prop="creditRating">
                  <el-input
                    v-model="formData.creditRating"
                    placeholder="请输入信用级别"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="业务联系人" prop="contactName">
                  <el-input
                    v-model="formData.contactName"
                    placeholder="请输入业务联系人"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input
                    v-model="formData.contactPhone"
                    placeholder="请输入联系电话"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.type == '3'">
                <el-form-item label="支付说明" prop="remark">
                  <el-input
                    v-model="formData.remark"
                    placeholder="请输入支付说明"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="附件" prop="applicationFileList">
                  <template #label="{ label }">
                    <div class="text-right">
                      {{ label }}
                    </div>
                    <el-popover
                      placement="top-start"
                      title="注意"
                      width="50%"
                      trigger="hover"
                    >
                      <template #reference>
                        <el-icon><QuestionFilled /></el-icon>
                      </template>
                      <div>
                        <p>
                          1、请附营业执照、法人身份证、开户银行、产品信息资质等相关证书、资质复印件+盖公章，可先扫描件存档，七个工作日内需提供纸质复印件。
                        </p>
                        <p>2、信息产品超过一项，需提供附件表（含价格）</p>
                        <p>
                          3.业务部门经理提交该表意见，应详细描述采纳该供应商原由
                        </p>
                        <p>
                          4.供应商财务状况可提供财务报表或审计报表扫描件（纸质或电子）
                        </p>
                        <p>
                          5.该表格由分公司内容自行审批完，扫描件提交省公司商务上传总部主数据系统
                        </p>
                        <p>
                          由于现所有信息都必须提交主数据系统，请各单位、部门将上述资料打包发送省公司作为申请资料。
                        </p>
                      </div>
                    </el-popover>
                  </template>
                  <el-upload
                    class="upload-demo"
                    action="#"
                    :before-upload="
                      file => beforeAvatarUpload(file, 'applicationFileList')
                    "
                    :http-request="
                      params => requestFile(params, 'applicationFileList')
                    "
                    :accept="uploadType['contract'].toString()"
                    :limit="10"
                    :show-file-list="false"
                  >
                    <!--
                accept=".rar, .zip, .doc, .docx, .pdf, .xls, .xlsx, .ppt, .pptx,.gif, .jpg, .jpeg, .png" -->
                    <el-button type="default" style="font-size: 14px"
                      ><el-icon><UploadFilled /></el-icon>上传</el-button
                    >
                    <template #tip>
                      <div class="el-upload__tip float-right">
                        {{
                          `支持格式${uploadType[
                            'contract'
                          ].toString()} ，单个文件不能超过20MB`
                        }}
                      </div>
                    </template>
                  </el-upload>
                  <div class="text-14px mt-10px" style="width: 100%">
                    <div
                      v-for="(item, index) in formData.applicationFileList"
                      :key="item.fileName"
                    >
                      <el-link
                        @click="viewFiles(item.url)"
                        :underline="false"
                        type="primary"
                        >{{ item.origFileName }}</el-link
                      >
                      <el-button
                        text
                        plain
                        @click="delFileName(index, 'applicationFileList')"
                        >删除</el-button
                      >
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 产品信息 -->
          <el-collapse-item name="2" disabled v-if="formData.type != '3'">
            <template #title>
              <TitleName
                title="产品信息"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <el-row :gutter="80">
              <el-col :span="24">
                <el-form-item label="产品名称" prop="supplierProduct">
                  <el-input
                    v-model="formData.supplierProduct"
                    type="textarea"
                    :rows="1"
                    placeholder="请输入产品名称"
                    maxlength="100"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="产品规格型号" prop="supplierSpecification">
                  <el-input
                    v-model="formData.supplierSpecification"
                    type="textarea"
                    :rows="1"
                    placeholder="请输入产品规格型号"
                    maxlength="100"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="初次询价价格" prop="supplierInquiryPrice">
                  <el-input
                    v-model="formData.supplierInquiryPrice"
                    placeholder="请输入初次询价价格"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="上传询价资料" prop="inquiryFileList">
                  <el-upload
                    class="upload-demo"
                    action="#"
                    :before-upload="
                      file => beforeAvatarUpload(file, 'inquiryFileList')
                    "
                    :http-request="
                      params => requestFile(params, 'inquiryFileList')
                    "
                    :accept="uploadType['contract'].toString()"
                    :limit="10"
                    :show-file-list="false"
                  >
                    <!--
                accept=".rar, .zip, .doc, .docx, .pdf, .xls, .xlsx, .ppt, .pptx,.gif, .jpg, .jpeg, .png" -->
                    <el-button type="default" style="font-size: 14px"
                      ><el-icon><UploadFilled /></el-icon>上传</el-button
                    >
                    <template #tip>
                      <div class="el-upload__tip float-right">
                        {{
                          `支持格式${uploadType[
                            'contract'
                          ].toString()} ，单个文件不能超过20MB`
                        }}
                      </div>
                    </template>
                  </el-upload>
                  <div class="text-14px mt-10px" style="width: 100%">
                    <div
                      v-for="(item, index) in formData.inquiryFileList"
                      :key="item.fileName"
                    >
                      <el-link
                        @click="viewFiles(item.url)"
                        :underline="false"
                        type="primary"
                        >{{ item.origFileName }}</el-link
                      >
                      <el-button
                        text
                        plain
                        @click="delFileName(index, 'inquiryFileList')"
                        >删除</el-button
                      >
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 评价项目 -->
          <el-collapse-item name="3" disabled v-if="formData.type != '3'">
            <template #title>
              <TitleName
                title="评价项目"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <el-row :gutter="80">
              <el-col :span="12">
                <el-form-item label="质量体系认证" prop="qualitySystem">
                  <el-radio-group v-model="formData.qualitySystem">
                    <el-radio
                      v-for="item in sys_have_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="相关证书/资质" prop="relevantCertificate">
                  <el-radio-group v-model="formData.relevantCertificate">
                    <el-radio
                      v-for="item in sys_have_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="品质异常记录" prop="abnormalQuality">
                  <el-radio-group v-model="formData.abnormalQuality">
                    <el-radio
                      v-for="item in sys_have_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="交货异常记录" prop="abnormalDelivery">
                  <el-radio-group v-model="formData.abnormalDelivery">
                    <el-radio
                      v-for="item in sys_have_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="服务与合作" prop="serviceCooperation">
                  <el-radio-group v-model="formData.serviceCooperation">
                    <el-radio
                      v-for="item in service_and_cooperation"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="近三年内有无重大违法记录"
                  prop="majorViolations"
                >
                  <template #label="{ label }">
                    <div class="w-full leading-5">{{ label }}</div>
                  </template>
                  <el-radio-group v-model="formData.majorViolations">
                    <el-radio
                      v-for="item in sys_have_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供货来源" prop="supplySource">
                  <el-radio-group v-model="formData.supplySource">
                    <el-radio
                      v-for="item in suppiler_supply_source"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="办公场所" prop="officeSpace">
                  <el-radio-group v-model="formData.officeSpace">
                    <el-radio
                      v-for="item in supplier_office_sapce"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="价格水平" prop="priceLevel">
                  <el-radio-group v-model="formData.priceLevel">
                    <el-radio
                      v-for="item in supplier_price_level"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="供应商人力资源情况（团队、员工素质）"
                  prop="manpowerSituation"
                >
                  <template #label="{ label }">
                    <div class="w-full leading-5">{{ label }}</div>
                  </template>
                  <el-radio-group v-model="formData.manpowerSituation">
                    <el-radio
                      v-for="item in supplier_evaluate_situation"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商务流程" prop="businessProcess">
                  <el-radio-group v-model="formData.businessProcess">
                    <el-radio
                      v-for="item in supplier_business_process"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="供应商知名度/美誉度"
                  prop="supplierVisibility"
                >
                  <template #label="{ label }">
                    <div class="w-full leading-5">{{ label }}</div>
                  </template>
                  <el-radio-group v-model="formData.supplierVisibility">
                    <el-radio
                      v-for="item in supplier_evaluate_situation"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品售前售后" prop="preAndAfter">
                  <el-radio-group v-model="formData.preAndAfter">
                    <el-radio
                      v-for="item in supplier_evaluate_situation"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商财务状况" prop="financialCondition">
                  <el-radio-group v-model="formData.financialCondition">
                    <el-radio
                      v-for="item in supplier_evaluate_situation"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="与公司往来付款条件" prop="paymentTerms">
                  <el-radio-group v-model="formData.paymentTerms">
                    <el-radio
                      v-for="item in supplier_payment_terms"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 市场考察 -->
          <el-collapse-item name="4" disabled v-if="formData.type != '3'">
            <template #title>
              <TitleName
                title="市场考察"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <el-row :gutter="80">
              <el-col :span="24">
                <el-form-item label="合作项目描述" prop="projectDescription">
                  <el-input
                    v-model="formData.projectDescription"
                    type="textarea"
                    :rows="1"
                    placeholder="请输入合作项目描述"
                    maxlength="100"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="准入市场分析" prop="marketAnalysis">
                  <el-input
                    v-model="formData.marketAnalysis"
                    type="textarea"
                    :rows="1"
                    placeholder="请输入准入市场分析"
                    maxlength="100"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <!-- 合作商机 -->
          <el-collapse-item name="4" disabled>
            <template #title>
              <TitleName
                title="合作商机"
                icon="i-carbon-bookmark-filled"
                class="text-#000"
              ></TitleName>
            </template>
            <el-row :gutter="80">
              <el-col :span="formData.taxControl == '0' ? 8 : 24">
                <el-form-item label="是否为我方税控用户" prop="taxControl">
                  <el-radio-group v-model="formData.taxControl">
                    <el-radio
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="16" v-if="formData.taxControl == '0'">
                <el-form-item label="其税控信息" prop="nonTaxControlReason">
                  <el-input
                    v-model="formData.nonTaxControlReason"
                    placeholder="其税控信息"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="采购我方产品" prop="purchaseProduct">
                  <el-radio-group v-model="formData.purchaseProduct">
                    <el-radio
                      v-for="item in sys_have_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="formData.purchaseProduct == '1'">
                <el-form-item label="我方产品名称" prop="productName">
                  <el-input
                    v-model="formData.productName"
                    placeholder="我方产品名称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="formData.purchaseProduct == '1'">
                <el-form-item label="金额" prop="productPrice">
                  <el-input
                    v-model="formData.productPrice"
                    placeholder="金额"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item
                  label="向其推荐公司产品"
                  prop="recommendedProduct"
                >
                  <el-input
                    v-model="formData.recommendedProduct"
                    placeholder="推荐公司产品"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </div>

    <!-- 提交审批 -->
    <SubmissionProcess
      :dialog-param="examineParam"
      :flowOptions="flowOptions"
      @initiate="handleClose('initiate')"
      @close="handleClose('examine')"
    ></SubmissionProcess>

    <!-- 物料选择弹窗 -->
    <SelectA8Supplier
      v-if="dialogParam.open"
      v-model="dialogParam.open"
      :dialogParam="dialogParam"
      @ok="a8SupplierFn"
    />
  </div>
</template>
<script setup name="SupplierForm">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useTagsViewStore from '@/store/modules/tagsView'
import { setSupplier, getSupplier } from '@/api/supplierManage/index'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import { isMoneyNot, validateLen } from '@/utils/validate'
import { skipToError, viewFile, hasPermi } from '@/utils/commo'
import useUserStore from '@/store/modules/user'
import SubmissionProcess from '@/businessComponents/SubmissionProcess'
import {
  listProcess,
  getBusinessProStatus,
  getNodeData
} from '@/api/workflow/process'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const { proxy, type } = getCurrentInstance()
const props = defineProps({
  supplierId: {
    type: [Number, String],
    require: true
  },
  id: {
    type: [Number, String],
    require: false
  }
})

const {
  yes_or_no,
  supplier_evaluate_situation,
  supplier_price_level,
  supplier_office_sapce,
  supplier_business_process,
  suppiler_supply_source,
  sys_have_no,
  supplier_payment_terms,
  supplier_type
} = proxy.useDict(
  'yes_or_no', //是否
  'supplier_evaluate_situation', //供应商评价情况
  'supplier_price_level', //供应商价格水平
  'supplier_office_sapce', //供应商办公场所
  'supplier_business_process', //供应商商务流程
  'suppiler_supply_source', //供应商供货来源
  'sys_have_no', //有无
  'supplier_payment_terms', //供应商付款条件
  'supplier_type' //--供应商来源
)
const supplier_type_1 = computed(() => {
  return supplier_type.value.filter(item => item.value != '2')
})
const service_and_cooperation = computed(() => {
  return supplier_evaluate_situation.value.filter(item => item.value != '2')
})
const data = reactive({
  loading: false,
  formData: {
    type: '1',
    formType: 'add',
    // deptId: userStore.userInfo.orgId,
    applicationFileList: [],
    inquiryFileList: []
  },
  formRules: {
    supplierName: [
      {
        required: true,
        message: '请输入供应商名称',
        trigger: 'blur'
      }
    ],
    supplierType: [
      {
        required: true,
        message: '请输入供应商来源',
        trigger: 'blur'
      }
    ],
    address: [
      {
        required: true,
        message: '请输入供应商地址',
        trigger: 'blur'
      }
    ],
    legalRepresentative: [
      {
        required: true,
        message: '请输入法定代表人',
        trigger: 'blur'
      }
    ],
    registeredCapital: [
      {
        required: true,
        message: '请输入注册资本',
        trigger: 'blur'
      }
    ],
    supplierTaxcode: [
      {
        required: true,
        message: '请输入统一社会信用代码',
        trigger: 'blur'
      }
    ],
    businessTerm: [
      {
        required: true,
        message: '请输入营业期限',
        trigger: 'blur'
      }
    ],
    depositBank: [
      {
        required: true,
        message: '请输入开户银行',
        trigger: 'blur'
      }
    ],
    bankAccount: [
      {
        required: true,
        message: '请输入银行账号',
        trigger: 'blur'
      }
    ],
    interbankNumber: [
      {
        required: true,
        message: '请输入联行号',
        trigger: 'blur'
      }
    ],
    creditScore: [
      {
        required: true,
        message: '请输入系统征信分值',
        trigger: 'blur'
      }
    ],
    creditRating: [
      {
        required: true,
        message: '请输入信用级别',
        trigger: 'blur'
      }
    ],
    contactName: [
      {
        required: true,
        message: '请输入业务联系人',
        trigger: 'blur'
      }
    ],
    contactPhone: [
      {
        required: true,
        message: '请输入联系电话',
        trigger: 'blur'
      }
    ],
    remark: [
      {
        required: true,
        message: '请输入支付说明',
        trigger: 'blur'
      }
    ],
    applicationFileList: [
      {
        required: true,
        message: '请上传附件',
        trigger: ['blur', 'change']
      }
    ],
    supplierProduct: [
      {
        required: true,
        message: '请输入产品名称',
        trigger: 'blur'
      }
    ],
    supplierSpecification: [
      {
        required: true,
        message: '请输入产品规格型号',
        trigger: 'blur'
      }
    ],
    supplierInquiryPrice: [
      {
        required: true,
        message: '请输入初次询价价格',
        trigger: 'blur'
      },
      {
        validator: isMoneyNot
      }
    ],
    inquiryFileList: [
      {
        required: true,
        message: '请上传询价资料',
        trigger: ['blur', 'change']
      }
    ],
    qualitySystem: [
      {
        required: true,
        message: '请选择质量体系认证',
        trigger: 'change'
      }
    ],
    relevantCertificate: [
      {
        required: true,
        message: '请选择相关证书/资质',
        trigger: 'change'
      }
    ],
    abnormalQuality: [
      {
        required: true,
        message: '请选择品质异常记录',
        trigger: 'change'
      }
    ],
    abnormalDelivery: [
      {
        required: true,
        message: '请选择交货异常记录',
        trigger: 'change'
      }
    ],
    serviceCooperation: [
      {
        required: true,
        message: '请选择服务与合作',
        trigger: 'change'
      }
    ],
    majorViolations: [
      {
        required: true,
        message: '请选择近三年内有无重大违法记录',
        trigger: 'change'
      }
    ],
    supplySource: [
      {
        required: true,
        message: '请选择供货来源',
        trigger: 'change'
      }
    ],
    officeSpace: [
      {
        required: true,
        message: '请选择办公场所',
        trigger: 'change'
      }
    ],
    priceLevel: [
      {
        required: true,
        message: '请选择价格水平',
        trigger: 'change'
      }
    ],
    manpowerSituation: [
      {
        required: true,
        message: '请选择供应商人力资源情况（团队、员工素质）',
        trigger: 'change'
      }
    ],
    businessProcess: [
      {
        required: true,
        message: '请选择商务流程',
        trigger: 'change'
      }
    ],
    supplierVisibility: [
      {
        required: true,
        message: '请选择供应商知名度/美誉度',
        trigger: 'change'
      }
    ],
    preAndAfter: [
      {
        required: true,
        message: '请选择产品售前售后',
        trigger: 'change'
      }
    ],
    financialCondition: [
      {
        required: true,
        message: '请选择供应商财务状况',
        trigger: 'change'
      }
    ],
    paymentTerms: [
      {
        required: true,
        message: '请选择与公司往来付款条件',
        trigger: 'change'
      }
    ],
    projectDescription: [
      {
        required: true,
        message: '请输入合作项目描述',
        trigger: 'blur'
      }
    ],
    marketAnalysis: [
      {
        required: true,
        message: '请输入准入市场分析',
        trigger: 'blur'
      }
    ],
    taxControl: [
      {
        required: true,
        message: '请选择是否为我方税控用户',
        trigger: 'change'
      }
    ],
    nonTaxControlReason: [
      {
        required: true,
        message: '请输入其税控信息',
        trigger: 'blur'
      }
    ],
    purchaseProduct: [
      {
        required: true,
        message: '请选择采购我方产品',
        trigger: 'change'
      }
    ],
    productName: [
      {
        required: true,
        message: '请输入我方产品名称',
        trigger: 'blur'
      }
    ],
    recommendedProduct: [
      {
        required: true,
        message: '请输入推荐产品',
        trigger: 'blur'
      }
    ],
    productPrice: [
      {
        required: true,
        message: '请输入金额',
        trigger: 'blur'
      },
      {
        validator: isMoneyNot
      }
    ]
  },
  formRulesA8: {
    supplierName: [
      {
        required: true,
        message: '请输入供应商名称',
        trigger: 'blur'
      }
    ],
    type: [
      {
        required: true,
        message: '请输入供应商来源',
        trigger: 'blur'
      }
    ],
    expireDate: [
      {
        required: true,
        message: '请输入到期时间',
        trigger: 'change'
      }
    ],
    supplierType: [
      {
        required: true,
        message: '请输入供应商来源',
        trigger: 'blur'
      }
    ],
    address: [
      {
        required: true,
        message: '请输入供应商地址',
        trigger: 'blur'
      }
    ],
    legalRepresentative: [
      {
        required: true,
        message: '请输入法定代表人',
        trigger: 'blur'
      }
    ],
    registeredCapital: [
      {
        required: true,
        message: '请输入注册资本',
        trigger: 'blur'
      }
    ],
    supplierTaxcode: [
      {
        required: true,
        message: '请输入统一社会信用代码',
        trigger: 'blur'
      }
    ],
    businessTerm: [
      {
        required: true,
        message: '请输入营业期限',
        trigger: 'blur'
      }
    ],
    depositBank: [
      {
        required: true,
        message: '请输入开户银行',
        trigger: 'blur'
      }
    ],
    bankAccount: [
      {
        required: true,
        message: '请输入银行账号',
        trigger: 'blur'
      }
    ],
    interbankNumber: [
      {
        required: true,
        message: '请输入联行号',
        trigger: 'blur'
      }
    ],
    creditScore: [
      {
        required: true,
        message: '请输入系统征信分值',
        trigger: 'blur'
      }
    ],
    creditRating: [
      {
        required: true,
        message: '请输入信用级别',
        trigger: 'blur'
      }
    ],
    contactName: [
      {
        required: true,
        message: '请输入业务联系人',
        trigger: 'blur'
      }
    ],
    contactPhone: [
      {
        required: true,
        message: '请输入联系电话',
        trigger: 'blur'
      }
    ],
    remark: [
      {
        required: true,
        message: '请输入支付说明',
        trigger: 'blur'
      }
    ],
    applicationFileList: [
      {
        required: true,
        message: '请上传附件',
        trigger: ['blur', 'change']
      }
    ]
  },
  activeNames: ['1', '2', '3', '4', '5']
})
let { loading, formData, formRules, formRulesA8, activeNames } = toRefs(data)

const isExamine = ref(true) // 判断是否走审批按钮
watch(
  [
    () => route.query.supplierId,
    () => route.query.supplierData,
    () => props.supplierId,
    () => props.id
  ],
  async val => {
    if (route.query.supplierId && route.name == type.name) {
      getFormData(route.query.supplierId)
    } else if (props.supplierId && route.name == 'EditSupplier') {
      await getFormData(props.supplierId)
      //根据业务查询审批状态
      await getBusinessProStatusFn()
      // 判断表单是否可编辑  获取当前流程节点
      let res = await getNodeData(props.supplierId)
      bpmnStatus.value = res.data?.nowTaskName
      formDisabled.value =
        res.data == null || res.data?.isFirst == 'Y' ? false : true
    } else if (props.id && route.name == 'WorkDetail') {
      await getFormData(props.id)
      // 获取流程节点数据
      if (route.query.processed) {
        // fieldDisabled.value
        let res = await getNodeData(props.id)
        if (res.code !== 200) return
        bpmnStatus.value = res.data?.nowTaskName
        // formDisabled.value =
        //   res.data == null || res.data?.isFirst == 'Y' ? false : true
        try {
          formDisabled.value = res.data?.formDisabled
        } catch (error) {}
        try {
          let resDis = res.data?.fieldDisabled
          fieldDisabled.value = resDis
            ? resDis.replaceAll(',', '，').split('，')
            : []
        } catch (error) {}
        try {
          let resHid = res.data?.fieldHidden
          fieldHidden.value = resHid
            ? resHid.replaceAll(',', '，').split('，')
            : []
        } catch (error) {}
      }
      formDisabled.value =
        !formDisabled.value && route.query.processed == 'true' ? false : true
      isCanStart.value = false
    } else if (route.name == type.name) {
      isExamine.value = true
      // 走业务流程
      initFlowFn('28')
    }
  },
  {
    immediate: true
  }
)

// 获取表单信息
async function getFormData(id) {
  loading.value = true
  let res = await getSupplier(id)
  if (res.code !== 200) return
  let resData = {}
  resData = res.data
  formData.value = resData
  loading.value = false
}

const dialogParam = ref({
  open: false
})
// 添加a8供应商
function addA8Supplier() {
  dialogParam.value.open = true
  dialogParam.value.productQuery = {}
}
// 确定添加A8供应商
function a8SupplierFn(val) {
  proxy.$refs.form.clearValidate()
  formData.value = {
    ...val[0],
    type: formData.value.type,
    formType: 'a8'
  }
}

// 保存
function handleSubmit(type) {
  return new Promise((resolve, reject) => {
    if (type == 'save' && formData.value.formType == 'add') {
      // 新增暂存
      proxy.$refs['form'].validateField(
        ['supplierName', 'supplierTaxcode'],
        err => {
          if (err) {
            setSupplier(formData.value).then(res => {
              getFormData(res.data.id)
              proxy.useReturn(
                '',
                () => {
                  //返回上一步
                  handleReturn()
                },
                async () => {
                  //继续
                }
              )
            })
          }
        }
      )
    } else if (type == 'save' && formData.value.formType == 'a8') {
      // a8准入
      proxy.$refs['form'].validate(valid => {
        if (valid) {
          setSupplier(formData.value).then(res => {
            getFormData(res.data.id)
            proxy.useReturn(
              '',
              () => {
                //返回上一步
                handleReturn()
              },
              async () => {
                //继续
              }
            )
          })
        } else {
          skipToError()
        }
      })
    } else if (type == 'examine') {
      proxy.$refs.form.validate(async (valid, msg) => {
        if (valid) {
          await saveForm(type, resolve(), reject())
        } else {
          skipToError()
        }
      })
    } else {
      // 流程中保存
      setSupplier(formData.value).then(res => {
        if (res.code !== 200) {
          reject(res)
          return
        }
        resolve(res)
        getFormData(res.data.id)
      })
    }
  })
}
// 保存表单
async function saveForm(type, resolve, reject) {
  resolve = resolve ? resolve() : () => {}
  reject = reject ? reject() : () => {}
  let res = await setSupplier(formData.value)
  if (res.code !== 200) {
    reject(res)
    return
  }
  resolve(res)
  await getFormData(res.data.id)
  // 审批流程id赋值
  examineParam.value.businessId = res.data.id

  handleExamine()
}
// 流程同意调用的方法
async function handleSave() {
  if (!formDisabled.value) {
    return await handleSubmit()
  }
}
const uploadType = {
  contract: ['.rar', '.zip', '.doc', '.docx', '.pdf', '.jpg', '.png', '.jpeg']
}
/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile, group) {
  console.log('rawFile==>', rawFile)
  console.log('group==>', group)
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = uploadType['contract'].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error(
      `上传文件只能是${uploadType['contract']
        .toString()
        .replace(/\./g, '')
        .replace(/,/g, '、')}格式!`
    )
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}
// 上传附件
function requestFile(params, group) {
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  // uploadData.append('bucketName', 'article')
  uploadFile(uploadData).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(`${res.data.origFileName}上传成功`)
      console.log('formData.value==>', formData.value)
      formData.value[group].push(res.data)
      console.log('formData.value[group]==>', formData.value[group])
    }
  })
}
// 删除附件
async function delFileName(index, group) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      // let fule = {
      //   // bucketName: 'article',
      //   fileName: formData.value[group][index].fileName
      // }
      const res = await delFile(formData.value[group][index].fileName)
      if (res.code === 200) {
        formData.value[group].splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
// 预览文件
function viewFiles(url) {
  viewFile(url, useUserStore().userInfo.nickName)
}

const examineParam = ref({}) // 传递的参数
const flowOptions = ref([]) // 该业务的流程数据
const isCanStart = ref(true) // 判断该业务是否可以审批发起 以及办理详情 访问的时候不能审批 ===》针对编辑页面  办理详情
const bpmnStatus = ref('') //表单标题
const formDisabled = ref(false) // 禁用表单
const fieldDisabled = ref([]) // 禁用字段
const fieldHidden = ref([]) // 隐藏字段
/***************************业务流程 模块 start****************************************************************/
/*****审批模块  start*** */
/**
 * 提交审批 按钮
 发布需要的参数 examineParam 参数说明
  visible弹出框是否显示
  businessId //业务id
  businessName//业务名称（如：项目模块 businessName：项目名称）
  amount// 流程设计里面设计的条件参数值
  categoryCode //==>流程分类 页面查看 分类编码：项目1，订单2 客户3 	投标4 采购13 销售14
/**
 * 提交审批 按钮
 */
const handleExamine = async () => {
  if (!examineParam.value.businessId) {
    proxy.$modal.msgWarning('请重新发起审批')
    return false
  }
  examineParam.value.businessName = `${formData.value.supplierName}准入申请` //标题
  examineParam.value.categoryCode = '28' //分类编码：项目1，订单2 客户3 	投标4
  examineParam.value.type = Number(formData.value.type) //判断供应商来源
  examineParam.value.initiateParams = {
    type: Number(formData.value.type) //判断供应商来源
  }
  examineParam.value.visible = true
}
// 关闭
const handleClose = type => {
  switch (type) {
    case 'examine':
      //弹出框关闭
      examineParam.value.visible = false
      break
    case 'initiate':
      //审批 发起成功
      isCanStart.value = false
      examineParam.value.visible = false
      handleReturn()
      break
  }
}
/*****审批模块  end*** */
/**
 * 业务流程整体思路：
 * 1.查询该业务是否有流程
 * 2.根据该业务流程来判断
 * * 2.1没有流程-提示不能新建数据
 * 3.点击发起申请【调组件】
 * * 只有一条流程时，下一环节人的显示 -再发起
 * * 多条流程时，选择流程，再选下一环节人的显示 -再发起
 * @param {*} type  业务类型 项目是1 订单业务2 	客户模块业务3 采购13
 */

async function initFlowFn(type) {
  // 1.查询该业务是否有流程
  let comRes = await listProcess({
    pageNum: 1,
    pageSize: 9999,
    category: type
  })
  flowOptions.value = comRes.rows || []
  // 2.根据
  if (JSON.stringify(flowOptions.value) == '[]') {
    //2.1 没有流程-提示不能新建数据
    if (route.name == type.name) {
      // 新建页面
      proxy.$modal.msgError('该业务没有配置流程，请先创建流程')
    } else {
      //编辑页面
      isExamine.value = false
    }
  } else {
    isExamine.value = true
  }
}
// 编辑页面的时候 -》根据业务查询审批状态
async function getBusinessProStatusFn() {
  let statusRes = await getBusinessProStatus({ businessId: formData.value.id })
  if (statusRes.data.canStart) {
    // canStart false时 不能发起，true则可以发起
    isCanStart.value = true
    initFlowFn('28')
  } else {
    isCanStart.value = false
  }
  // if (statusRes.data.status) {
  //   // status判断流程环节05表示结束
  //   isCanStart.value = true
  // } else {
  //   isCanStart.value = false
  // }
}
/***************************业务流程 模块 end****************************************************************/

// 初始化
function init() {}

// 改变来源清空表单
const typeChange = val => {
  proxy.$refs.form.resetFields()
  // formData.value.type = val
  // formData.value.formType = 'add'
  formData.value = {
    type: val,
    formType: 'add',
    applicationFileList: [],
    inquiryFileList: []
  }
  proxy.$refs.form.clearValidate()
}

init()
// 返回、关闭页面
function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}
//暴露出保存方法
defineExpose({ handleSave })
</script>
<style scoped>
.form-box :deep(.w-full) {
  width: 100%;
}
/* .order-form :deep(.avue-crud__menu) {
  border-bottom: 1px solid #eee;
} */
.form-box .el-collapse {
  border-top: none;
}
.form-box:deep(.form-title:before) {
  content: '▋';
  display: inline-block;
  color: #409eff;
}

:deep(.avue-crud__empty) {
  padding: 0;
}
</style>
